<template>
  <div>
    <!-- 查询组件 -->
    <el-form :inline="true" :model="searchMap" ref="ruleForm" class="demo-form-inline">
        <el-form-item prop='name'>
            <el-input v-model="searchMap.name" placeholder="商品名称"></el-input>
        </el-form-item>
        <el-form-item prop='code'>
            <el-input v-model="searchMap.code" placeholder="商品编号"></el-input>
        </el-form-item>
        <!-- 引入供应商组件，以弹窗形式选择供应商 -->
        <el-form-item prop='supplierName'>
            <el-input v-model="searchMap.supplierName" readonly placeholder="选择供应商" @click.native='supplierList'></el-input>
        </el-form-item>
        <el-form-item>
            <!-- 查询 -->
            <el-button type='primary' icon="el-icon-search" circle @click="inquireGoods"></el-button>
            <!-- 新增 -->
            <el-button type="info" icon='el-icon-edit-outline' circle @click="addBefore"></el-button>
            <!-- 重置 -->
            <el-button icon='el-icon-refresh' circle @click="resetForm('ruleForm')"></el-button>
        </el-form-item>
    </el-form>

    <!-- 表格组件 -->
    <el-table
      :data="tableData"
      border
      stripe
      max-height='520'
      style="width: 100%">
      <el-table-column
          fixed
          type='index'
          label="序号"
          width="60">
      </el-table-column>
      <el-table-column
          prop="code"
          label="商品编码"
          min-width="240">
      </el-table-column>
      <el-table-column
          prop="name"
          label="商品名称"
          min-width="240">
      </el-table-column>
      <el-table-column
          prop="spec"
          label="商品规格"
          width="120">
      </el-table-column>
      <el-table-column
          prop="retailPrice"
          label="零售价"
          width="120">
      </el-table-column>
      <el-table-column
          prop="purchasePrice"
          label="进货价"
          width="120">
      </el-table-column>
      <el-table-column
          prop="storageNum"
          label="库存数量"
          width="120">
      </el-table-column>
      <el-table-column
          prop="supplierName"
          label="供应商"
          width="200">
      </el-table-column>
      <el-table-column
          fixed="right"
          label="操作"
          width="100">
          <template slot-scope="scope">
              <!-- scope.row：当前行的商品的所有信息 -->
              <el-button @click="editBefore(scope.row.id)" type="success" size="small" icon="el-icon-edit" circle></el-button>
              <el-button @click="deleteGoods(scope.row.id)" type="danger" size="small" icon="el-icon-delete" circle></el-button>
          </template>
      </el-table-column>
    </el-table>

    <!-- 新增、编辑商品弹窗 -->
    <el-dialog :title="goodsId?'编辑商品':'新增商品'" :visible.sync="dialogFormVisible" width='680px'>
        <el-form :model="goodsForm" ref='goodsform' :rules="rules" status-icon>
            <el-form-item prop='name' label="商品名称" :label-width="formLabelWidth" style='width:550px'>
                <el-input v-model="goodsForm.name" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item prop='code' label="商品编码" :label-width="formLabelWidth" style='width:550px'>
                <el-input v-model="goodsForm.code" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item prop='spec' label="商品规格" :label-width="formLabelWidth" style='width:550px'>
                <el-input v-model="goodsForm.spec" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item prop='retailPrice' label="零售价" :label-width="formLabelWidth" style='width:550px'>
                <el-input v-model="goodsForm.retailPrice" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item prop='purchasePrice' label="进货价" :label-width="formLabelWidth" style='width:550px'>
                <el-input v-model="goodsForm.purchasePrice" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item prop='storageNum' label="库存" :label-width="formLabelWidth" style='width:550px'>
                <el-input v-model="goodsForm.storageNum" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item prop='supplierName' label="供应商" :label-width="formLabelWidth" style='width:550px'>
                <el-input v-model="goodsForm.supplierName" readonly placeholder="选择供应商" @click.native='supplierList'></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible=false">取消</el-button>
            <el-button type="primary" @click="goodsId?editGoods():addGoods()">确定</el-button>
        </div>
    </el-dialog>

    <!-- 供应商列表弹窗 -->
    <el-dialog title="选择供应商" :visible.sync="dialogSupplierVisible" width='680px'>
      <!-- 组件通讯之父传子：在父组件绑定自定义属性isShow，到子组件用props接收 -->
      <!-- 组件通讯之子传父：在父组件的组件元素Supplier上绑定自定义事件option-supplier，当子组件触发该自定义事件时，就会执行optionSupplier方法 -->
      <Supplier :isShow='true' @option-supplier='optionSupplier'></Supplier>
    </el-dialog>

    <!-- 分页组件 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>
  </div>
</template>

<script>
import Supplier from '../supplier'

export default {
  components:{
    Supplier
  },
  data(){
    return{
      /* 商品列表数据 */
      tableData:[],
      /* 当前页、条数、总条数、查询条件 */
      currentPage:1,
      pageSize:10,
      total:0,
      searchMap:{
          name:'',
          code:'',
          supplierName:''
      },
      /* 编辑、新增开关 */
      goodsId:null,
      /* 商品填写信息 */
      goodsForm:{
        name: '',
        code: '',
        spec: '',
        retailPrice: 0.0,
        purchasePrice: 0.0,
        storageNum: 0,
        supplierName: ''
      },
      dialogFormVisible:false,
      formLabelWidth:'140px',
      /* 正则 */
      rules:{
        name: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        code: [
          { required: true, message: "商品编码不能为空", trigger: "blur" }
        ],
        retailPrice: [
          { required: true, message: "零售价不能为空", trigger: "blur" }
        ]
      },
      /* 供应商弹窗 */
      dialogSupplierVisible:false,
      /* 供应商选择的新增编辑与查询的开关 */
      isEdit:false
    }
  },
  methods:{
    async getSearch(){
      const {data} = await this.$request({
        url:`goods/list/search/${this.currentPage}/${this.pageSize}`,
        data:this.searchMap
      })
      this.tableData = data.data.rows;
      this.total = data.data.total;
    },
    /* 2.编辑前 */
    async editBefore(id){
      /* 打开弹出框，根据id发送请求获取该商品信息，并渲染到表单上 */
      this.isEdit = true
      this.dialogFormVisible = true;
      this.$nextTick(() => {
          this.$refs["goodsform"].clearValidate();
      });
      this.goodsId = id;
      const {data} = await this.$request({
          url:`/goods/${id}`,
          method:'get'
      });
      if(data.flag){
        this.goodsForm = data.data;
      }else{
        this.$notify({
            title: '失败',
            message: '获取商品信息失败！',
            type: 'error'
        });
      }
    },
    /* 3.添加前 */
    addBefore(){
      this.isEdit = true
      this.goodsId = null;
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["goodsform"].resetFields();
      });
    },
    /* 4.删除商品 */
    async deleteGoods(id){
      try{
        let result =  await this.$confirm('此操作将永久该商品信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
        })
        /* 发送请求 */
        const {data} = await this.$request({
            url:`/goods/${id}`,
            method:'delete'
        })
        /* 根据返回信息进行对应操作 */
        if(data.flag){
            this.$notify({
                title: '成功',
                message: '删除成功！',
                type: 'success'
            });
            /* 删除成功后重新发送请求渲染列表 */
            this.getSearch();
        }else{
            this.$notify({
                title: '失败',
                message: '删除商品失败，请稍后重新删除！',
                type: 'error'
            });
        }
      }catch(err){
          this.$notify.info({
              title: '取消',
              message: '已取消删除！'
          });
      }
    },
    /* 5.查询商品 */
    inquireGoods(){
      /* 只有填写任意非空条件才能发送查询请求 */
      if(this.searchMap.name || this.searchMap.code || this.searchMap.supplierName){
        this.getSearch();
      }else{
        this.$notify.info({
            title: '无效操作',
            message: '请输入查询条件再进行查询！'
        });
      }
    },
    /* 6.重置查询框 */
    resetForm(formName){
      this.$refs[formName].resetFields();
    },
    /* 7.更改每页条数 */
    handleSizeChange(size){
      this.pageSize = size;
      /* 重置显示第一页 */
      this.currentPage = 1;
      this.getSearch();
    },
    /* 8.更改当前页 */
    handleCurrentChange(page){
      this.currentPage = page;
      this.getSearch();
    },
    /* 9.新增商品 */
    addGoods(){
      /* 正则校验 */
      this.$refs['goodsform'].validate(async (valid) => {
          /* 正则校验通过则发送添加ajax请求 */
          if(valid){
              const {data} = await this.$request({
                  url:`/goods`,
                  method:'post',
                  data:this.goodsForm
              })
              /* 根据返回信息提示是否添加成功 */
              if(data.flag){
                  this.$notify({
                      title: '成功',
                      message: '添加商品成功！',
                      type: 'success'
                  });
                  /* 添加成功则清空表单，重新发送请求渲染列表为最新的信息 */
                  this.$refs['goodsform'].resetFields();
                  this.getSearch();
              }else{
                  this.$notify({
                      title: '失败',
                      message: '添加商品失败，请稍后重新添加！',
                      type: 'error'
                  });
                  return;
              }
          /* 不通过则提示修改内容 */
          }else{
              this.$notify({
                  title: '失败',
                  message: '必填项未填写或者填写内容不符合要求！',
                  type: 'error'
              });
              return;
          }
          this.dialogFormVisible = false;
      });
    },
    /* 10.供应商列表选择 */
    supplierList(){
      this.dialogSupplierVisible = true
    },
    /* 11. 接收子组件supplier传递过来的数据 */
    optionSupplier(data){
      if(this.isEdit){
        this.goodsForm.supplierName = data.name;
        this.goodsForm.supplierID = data.id;
      }else{
        this.searchMap.supplierName = data.name;
        this.searchMap.supplierID = data.id;
      }
      this.dialogSupplierVisible = false;
      /* 重置开关 */
      this.isEdit = false;
    },
    /* 12.编辑商品 */
    editGoods(){
      this.$refs['goodsform'].validate(async (valid) => {
          /* 正则校验通过则发送修改ajax请求 */
          if(valid){
              const {data} = await this.$request({
                  url:`/goods/${this.goodsId}`,
                  method:'put',
                  data:this.goodsForm
              })
              /* 根据返回信息提示是否修改成功 */
              if(data.flag){
                  this.$notify({
                      title: '成功',
                      message: '修改商品成功！',
                      type: 'success'
                  });
                  /* 修改成功则清空表单，重新发送请求渲染列表为最新的信息 */
                  this.$refs['goodsform'].resetFields();
                  this.getSearch();
              }else{
                  this.$notify({
                      title: '失败',
                      message: '修改商品失败，请稍后重新修改！',
                      type: 'error'
                  });
                  return;
              }
          /* 不通过则提示修改内容 */
          }else{
              this.$notify({
                  title: '失败',
                  message: '必填项未填写或者填写内容不符合要求！',
                  type: 'error'
              });
              return;
          }
          this.dialogFormVisible = false;
      });
    }
  },
  /* 1.获取默认列表数据 */
  created(){
    this.getSearch();
  }
}
</script>

<style>

</style>